import { Component, Input, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { ApesModalRef, ApesModalService } from '@shared/apes/modal';
import { deepClone, replaceAll } from '../../utils/utils';
import { UserAuthService } from '@core/services/user-auth.service';
import { FormGroup } from '@angular/forms';
import { ApesPreviewDialogComponent } from '@shared/ag-grid-ext/upload-component/apes-previewDialog.component';


@Component({
  selector: 'dialog-price-advance',
  templateUrl: './dialog-price-advance.component.html',
})
export class DialogPriceAdvanceComponent implements OnInit {
  model: any = {};
  options: any;
  resultsData: any = [];

  body: any = {};

  @Input() conditionModel: any;
  @Input() gridData: any;

  vin: any;
  carConfiguration: any;
  vehicle: any;

  id: string;                               // 方案号

  isLoading: boolean = false;
  tabSetIndex: any = 0;
  inquiryInitData: any = {};
  inquiryLeftData: any[] = [];
  inquiryRightData: any[] = [];
  inquiryShowData: any[] = [];
  postTotal: any = 0;

  inquiryTotal: any = 0;
  quoted: any = 0;
  showHidden: boolean = false;
  multiple: boolean = true;

  filterField: any = [
    { type: 'YSPMC', name: '配件' }, // 配件
    { type: 'supplier', name: '供应商代码' }, // 供应商
  ];


  constructor(private apiService: ApiService,
              protected userService: UserAuthService,
              private msg: ApesMessageService,
              private modalService: ApesModalService,
              public modal: ApesModalRef) {

  }

  ngOnInit() {
    this.initModelData();
    this.getInquiryData();
  }

  initModelData() {
    let setData = deepClone(this.conditionModel);
    this.vin = setData['customerCar']['vin'];
    this.carConfiguration = setData['carConfiguration'] ? setData['carConfiguration']['id'] + '/' + setData['carConfiguration']['name'] : '';
  }

  getInquiryData() {
    let api = 'fn.priceForwardService.queryPriceForwardOE';
    let setData = deepClone(this.conditionModel);
    let platform = this.userService.getUserInfoObj() ? this.userService.getUserInfoObj().platform : '';
    const data = { ...setData, platform: platform };
    this.isLoading = true;
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          console.log(body.item);
          this.inquiryInitData = body;
          this.inquiryLeftData = body.item;
          this.inquiryRightData = this.filtrationSelect(body.item);
          this.inquiryShowData = deepClone(this.inquiryRightData);
          this.filterCondition();
          // if (this.conditionModel.hasOwnProperty('node')) {
          //   this.checkFiltrationData();
          // }
        }
        this.isLoading = false;
        // this.onSelectionChanged(this.inquiryRightData);
        // console.log('返回数据', this.inquiryInitData);
      });
  }

  filtrationSelect(params) {
    let param = deepClone(params);
    param.forEach((com) => {
      let brand = [];
      let showTyre = com['type'] == 'Tyre';
      com.item.forEach((list) => {
        if (showTyre) {
          list.showTyre = showTyre;
          let check = true;
          brand.forEach((b) => {
            if (b.id == list.spBrand['id']) {
              check = false;
            }
          });
          if (check) {
            brand.push(list.spBrand);
          }
        }
        let selectFlag = 0;
        // if (list.hasOwnProperty('WYZ')) {
        //   let gridData = deepClone(this.gridData);
        //   gridData.forEach((data) => {
        //     if (data.hasOwnProperty('uniqueValue') && data['uniqueValue'] == list['WYZ']) {
        //       selectFlag = 1;
        //     }
        //   });
        // } else {
        //   selectFlag = 0;
        // }
        list.selectFlag = selectFlag;
      });
      if (showTyre) {
        com.brand = brand;
      }
    });
    return param;
  }

  brandChange(e, param) {
    console.log(param);
  }

  checkLogisticsMode(param) {
    let item = param['logisticsModeItems'];
    if (item.length <= 1) {
      param['logisticsLoading'] = true;
      let api = 'fn.servicePlanceService.queryCarrierFrom';
      let setData = {
        'EXTERNAL_GYSID': param['EXTERNAL_GYSID'],
        'MDID': param['MDID'],
      };
      this.apiService.post(api, setData).subscribe((body) => {
        console.log(body);
        param['logisticsLoading'] = false;
        param['logisticsModeItems'] = body;
      });
    }
  }

  filterCondition() {

    this.filterField.forEach((field) => {
      field.data = [];
      field.data = this.filtrationData(field.type);
    });
  }

  filtrationData(type) {
    let showData = [];
    let list = deepClone(this.inquiryLeftData);
    list.forEach((data) => {
      if (type == 'YSPMC') {
        let check = true;
        showData.forEach((sd) => {
          if (sd[type] == data[type]) {
            check = false;
          }
        });
        if (check) {
          let checked = true;
          showData.push({ [type]: data[type], checked: checked });
        }
      } else {
        data.item.forEach((res) => {
          let check = true;
          showData.forEach((sd) => {
            if (sd[type] == res[type]) {
              check = false;
            }
          });
          if (check) {
            let checked = true;
            showData.push({ [type]: res[type], checked: checked });
          }
        });
      }

    });
    return showData;
  }

  showImg(param){
    let value = deepClone(param.png);
    if (value) {
      value = replaceAll(value, '\"', '"');
    }
    let dialog: any = ApesPreviewDialogComponent;
    let fileList = JSON.parse(value) || [];
    let option = {
      title: '预览图片',
      _fileList: fileList,
    };

    this.openUploadDialog(option, (result: any) => {
    }, dialog);
  }

  openUploadDialog(option: any, callback: any, dialog?: any) {

    let body: any = { ...option };

    const openDialog = dialog ? dialog : ApesPreviewDialogComponent;
    const dialogRef = this.modalService.create({
      apesWidth: '45vw',
      apesTitle: body.title,
      apesContent: openDialog,
      apesComponentParams: body,
      apesFooter: [
        {
          label: '取消',
          type: 'default',
          onClick: (componentInstance) => {
            dialogRef.destroy(componentInstance['fileList']);
            // dialogRef.close();
          },
        },
        {
          label: '确定',
          type: 'primary',
          onClick: (componentInstance) => {
            // console.log(componentInstance);
            dialogRef.destroy(componentInstance['fileList']);
          },
        },
      ],
    });

    return dialogRef.afterClose.subscribe((result) => callback(result));
  }

  checkFiltrationData(type) {
    // console.log(this.filterField);
    let show = true;
    let list = deepClone(this.inquiryRightData);
    if (type == 'YSPMC') {
      list = list.filter((item) => {
        return this.filter(item, type);
      });
      if (list.length != 0) {
        show = false;
      }
    } else {
      list.forEach((data) => {
        data.item = data.item.filter((item) => {
          return this.filter(item, type);
        });
        if (data.item.length != 0) {
          show = false;
        }
      });
    }
    this.inquiryShowData = list;
    this.showInquiry = show;
  }

  showInquiry: boolean = false;

  filter(filterData, type) {
    let check = true;
    this.filterField.forEach((field) => {
      let type = field.type;
      field.data.forEach((data) => {
        if (data[type] == filterData[type] && check != false) {
          check = data.checked;
        }
      });
    });
    return check;
  }

  selectProduct(data, list) {

    data.selectFlag = data.selectFlag == 0 ? 1 : 0;

    this.inquiryRightData.forEach((res) => {
      if (res.YSPID == list.YSPID) {
        res.item.forEach((re) => {
          if (re.quoteResultId == data.quoteResultId) {
            // if (re.WYZ == data.WYZ && data.selectFlag == 1) {
            re.selectFlag = data.selectFlag;
            // re['logisticsMode'] = data['logisticsMode'];
            // if (!re.hasOwnProperty('refactorData') || re.refactorData == undefined) {
            //   this.postTotal = this.postTotal + 1;
            //   this.resultsData = [];
            //   this.getInquiryPoolItem(re, (reData) => {
            //     re['refactorData'] = reData;
            //     this.postTotal = this.postTotal - 1;
            //     if (this.postTotal == 0) {
            //       this.onSelectionChanged(this.inquiryRightData);
            //     }
            //   });
            // } else {
            //   if (re.refactorData.hasOwnProperty('logisticsMode')) {
            //     re.refactorData['logisticsMode'] = data['logisticsMode'];
            //   }
            // }
            // } else {
            //   re.selectFlag = 0;
            // }
          }
        });
      }
    });

    this.onSelectionChanged(this.inquiryRightData);
  }

  // getInquiryPoolItem(data, callBack) {
  //   let api = 'fn.service.getInquiryPoolItem';
  //   let setData = { 'PUR_SPXJDMX': [data], ...this.conditionModel };
  //
  //   this.apiService.post(api, { 'body': JSON.stringify(setData) }).subscribe(
  //     (body) => {
  //       // console.log(body);
  //       if (body) {
  //         callBack(body[0]);
  //       }
  //     });
  // }

  onSelectionChanged(selectedRow) {

    const data = [];
    selectedRow.forEach((list) => {
      list.item.forEach((item) => {
        if (item.selectFlag == 1) {
          data.push(item);
        }
      });
    });
    this.resultsData = data;
  }

  destroyModal(): void {
    this.modal.destroy(this.resultsData);
    3;
  }

  openShowHidden() {
    this.showHidden = !this.showHidden;
  }

  resetCondition() {
    this.tabSetIndex = 0;
    this.filterField.forEach((field) => {
      field.data.forEach((data) => {
        data.checked = true;
      });
    });
    this.inquiryShowData = deepClone(this.inquiryRightData);
    this.showInquiry = false;
  }

}
